package com.xueyi.game.backend.service.impl;

import com.xueyi.core.constants.IsStatus;
import com.xueyi.core.expection.BusinessException;
import com.xueyi.core.utils.LogUtil;
import com.xueyi.game.backend.config.BaseSqlConfig;
import com.xueyi.game.backend.config.GatewayConfig;
import com.xueyi.game.backend.entity.dto.AddOrUpdateJurisdictionDto;
import com.xueyi.game.backend.entity.dto.DeleteJurisdictionByIdDto;
import com.xueyi.game.backend.entity.dto.FindAllJurisdictionDto;
import com.xueyi.game.backend.entity.dto.RemoveMenuByIdDto;
import com.xueyi.game.backend.entity.po.BaseMenu;
import com.xueyi.game.backend.entity.po.BaseUser;
import com.xueyi.game.backend.entity.vo.BaseMenuVo;
import com.xueyi.game.backend.entity.vo.BaseSelectVo;
import com.xueyi.game.backend.mapper.BaseJurisdictionMapper;
import com.xueyi.game.backend.service.BaseJurisdictionService;
import com.xueyi.game.backend.service.IBackendRoleService;
import com.xueyi.game.backend.utils.BaseUserUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: hxs
 * @createDate: 2022/11/9 16:10
 * @description: TODO
 */
@Service
@Slf4j
@AllArgsConstructor
public class BaseJurisdictionServiceImpl implements BaseJurisdictionService {

    private final BaseJurisdictionMapper baseJurisdictionMapper;
    private final BaseSqlConfig baseSqlConfig;
    private final BaseUserUtil baseUserUtil;
    private final LogUtil logUtil;
    private final IBackendRoleService backendRoleService;

    /**
     * 获取所有的权限
     *
     * @param findAllJurisdictionReq
     * @return
     * @author: hxs
     */
    @Override
    public List<BaseMenuVo> findAllJurisdiction(FindAllJurisdictionDto findAllJurisdictionReq) {
        //获取所有的权限、菜单
        List<BaseMenuVo> list = baseJurisdictionMapper.findAllJurisdiction(findAllJurisdictionReq.getAuthorityType(), baseSqlConfig.getMenuTableName(), findAllJurisdictionReq.getIsValid());

        //创建权限列表、菜单列表
        List<BaseMenuVo> jurisdictionList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            Map<Integer, List<BaseMenuVo>> map = list.stream().collect(Collectors.groupingBy(BaseMenuVo::getParentId));
            jurisdictionList = findChildrenList(map, 0);

        }
        return jurisdictionList;
    }

    /**
     * 新增权限
     *
     * @param addOrUpdateJurisdictionReq
     * @return
     * @author: hxs
     */
    @Override
    public void addJurisdiction(AddOrUpdateJurisdictionDto addOrUpdateJurisdictionReq) throws BusinessException {
        //校验参数
        addOrUpdateJurisdictionReq.format();

        //封装参数
        BaseMenu baseMenu = new BaseMenu();
        baseMenu.setMenuIcon(addOrUpdateJurisdictionReq.getMenuIcon());
        baseMenu.setIsValid(IsStatus.YES);
        baseMenu.setMenuName(addOrUpdateJurisdictionReq.getMenuName());
        baseMenu.setMenuPath(addOrUpdateJurisdictionReq.getMenuPath());
        baseMenu.setAuthorityType(addOrUpdateJurisdictionReq.getAuthorityType());
        baseMenu.setParentId(addOrUpdateJurisdictionReq.getParentId());
        baseMenu.setOrdered(addOrUpdateJurisdictionReq.getOrdered());

        //插入到数据库
        baseJurisdictionMapper.addJurisdiction(baseMenu, baseSqlConfig.getMenuTableName());

        logUtil.info("新增了权限 【{}】", baseMenu.getMenuName());

        BaseUser user = GatewayConfig.USER_LOCAL.get();
        baseUserUtil.saveLog(user.getId() + "", "【权限管理】用户：" + user.getuName() + " 新增了权限 " + addOrUpdateJurisdictionReq.getMenuName());


    }

    /**
     * 修改权限
     *
     * @param addOrUpdateJurisdictionReq
     * @return
     * @author hxs
     */
    @Override
    public void updateJurisdiction(AddOrUpdateJurisdictionDto addOrUpdateJurisdictionReq) throws BusinessException {
        //参数校验
        addOrUpdateJurisdictionReq.format();

        //封装参数
        BaseMenu baseMenu = new BaseMenu();
        baseMenu.setMenuIcon(addOrUpdateJurisdictionReq.getMenuIcon());
        baseMenu.setMenuName(addOrUpdateJurisdictionReq.getMenuName());
        baseMenu.setMenuPath(addOrUpdateJurisdictionReq.getMenuPath());
        baseMenu.setAuthorityType(addOrUpdateJurisdictionReq.getAuthorityType());
        baseMenu.setParentId(addOrUpdateJurisdictionReq.getParentId());
        baseMenu.setId(addOrUpdateJurisdictionReq.getId());

        //修改数据库数据
        baseJurisdictionMapper.updateJurisdiction(addOrUpdateJurisdictionReq, baseSqlConfig.getMenuTableName());
        logUtil.info("修改了权限 {}【{}】", baseMenu.getId(), baseMenu.getMenuName());

        //查询所有关联的当前权限的角色
        String roleIds = baseJurisdictionMapper.findRolesByMenuId(baseMenu.getId(), baseSqlConfig.getAuthorityTableName());
        if (StringUtils.hasLength(roleIds)) {
            //清除缓存
            backendRoleService.removeCacheAfterChangeRole(roleIds);
        }
        BaseUser user = GatewayConfig.USER_LOCAL.get();
        baseUserUtil.saveLog(user.getId() + "", "【权限管理】用户：" + user.getuName() + " 修改了权限 " + addOrUpdateJurisdictionReq.getId() + " 的信息");

    }

    /**
     * 获取所有的顶级菜单
     *
     * @return
     * @author hxs
     */
    @Override
    public List<BaseSelectVo> findAllFatherMenu(Integer type) {
        return baseJurisdictionMapper.findAllFatherMenu(type, baseSqlConfig.getMenuTableName());
    }

    /**
     * 删除权限
     *
     * @param deleteJurisdictionByIdReq
     * @return
     * @author hxs
     */
    @Override
    public void deleteJurisdictionById(DeleteJurisdictionByIdDto deleteJurisdictionByIdReq) {
        if (deleteJurisdictionByIdReq.getIsValid().equals(1)) {
            deleteJurisdictionByIdReq.setIsValid(0);
        } else {
            deleteJurisdictionByIdReq.setIsValid(1);
        }
        baseJurisdictionMapper.deleteJurisdictionById(deleteJurisdictionByIdReq.getId(), deleteJurisdictionByIdReq.getIsValid(), baseSqlConfig.getMenuTableName());
        logUtil.info("删除了权限【{}】", deleteJurisdictionByIdReq.getId());


        BaseUser user = GatewayConfig.USER_LOCAL.get();
        if (deleteJurisdictionByIdReq.getIsValid().equals(1)) {
            baseUserUtil.saveLog(user.getId() + "", "【权限管理】用户：" + user.getuName() + " 修改了权限 " + deleteJurisdictionByIdReq.getId() + " 状态为正常 ");
        } else {
            baseUserUtil.saveLog(user.getId() + "", "【权限管理】用户：" + user.getuName() + " 修改了权限 " + deleteJurisdictionByIdReq.getId() + " 状态为禁用 ");
        }

    }

    /**
     * 物理删除权限
     *
     * @param removeMenuByIdReq
     * @return
     * @author hxs
     */
    @Override
    public void removeMenuById(RemoveMenuByIdDto removeMenuByIdReq) {
        baseJurisdictionMapper.removeMenuById(removeMenuByIdReq.getMenuId(), baseSqlConfig.getMenuTableName());
        logUtil.info("物理删除了权限【{}】", removeMenuByIdReq.getMenuId());

        BaseUser user = GatewayConfig.USER_LOCAL.get();
        baseUserUtil.saveLog(user.getId() + "", "【权限管理】用户：" + user.getuName() + " 物理删除了权限 " + removeMenuByIdReq.getMenuId());

    }

    /**
     * 通过递归封装权限的数据结构
     *
     * @param map 权限map
     * @param pid pid
     */
    private List<BaseMenuVo> findChildrenList(Map<Integer, List<BaseMenuVo>> map, Integer pid) {
        List<BaseMenuVo> flag = map.get(pid);
        if (!CollectionUtils.isEmpty(flag)) {
            flag.sort(((o1, o2) -> o2.getOrdered() - o1.getOrdered()));
            for (BaseMenuVo baseMenu : flag) {
                baseMenu.setChildren(findChildrenList(map, baseMenu.getId()));
            }
            return flag;
        } else {
            return new ArrayList<>();
        }
    }


}
